<template>
    <div>
        <!-- 头部标题 -->
        <van-nav-bar left-arrow title="个人信息" @click-left="$router.back()" right-text="保存" @click-right="onClickRight" />
        <!-- 信息区域一 -->
        <van-cell-group>
            <van-cell @click="openUpload" title="头像" is-link>
                <template #default>
                    <img class="userImg" :src="userObj.photo" alt="">
                </template>
            </van-cell>
            <van-cell @click="changeName" title="昵称" is-link :value="userObj.name" />
            <van-cell title="介绍" is-link :value="userObj.intro" />
        </van-cell-group>
        <!-- 信息区域二 -->
        <van-cell-group style="margin-top: 20px;">
            <van-cell title="性别" is-link :value="userObj.gender === 0 ? '男': '女'" />
            <van-cell title="生日" is-link :value="userObj.birthday" />
        </van-cell-group>
        <!-- 添加一个昵称的修改面板 -->
        <van-popup v-model="showname" position="bottom" :style="{ height: '7%' }">
            <van-field required v-model="userObj.name" placeholder="请输入用户名" />
        </van-popup>
        <!-- 头像上传组件 -->
        <upload @changephoto="v=>userObj.photo=v" ref="upload" />
    </div>
</template>

<script>
// 导入操作用户的方法
import { apiGetUser, apiGetprofile, apiUpdateprofile } from '../../api/user'
// 导入组件
import upload from './com/upload'
export default {
  data () {
    return {
      userObj: {
        name: '',
        photo: '',
        gender: '',
        birthday: '',
        intro: ''
      },
      // 控制 name 面板的显示和隐藏
      showname: false
    }
  },
  methods: {
    // 打开头像上传面板
    openUpload () {
      this.$refs.upload.show = true
    },
    async onClickRight () {
      try {
        // 将修改后的用户信息提交到服务器
        await apiUpdateprofile({
          name: this.userObj.name,
          gender: this.userObj.gender,
          birthday: this.userObj.birthday,
          intro: this.userObj.intro
        })
        // 提示修改成功
        this.$toast.success('修改成功')
      } catch (err) {
        this.$toast.fail(err.message)
      }
    },
    // 点击昵称打开昵称的修改面板
    changeName () {
      this.showname = true
    }
  },
  async mounted () {
    // 得到用户自己的信息
    var res1 = await apiGetUser()
    this.userObj.photo = res1.data.data.photo
    this.userObj.name = res1.data.data.name
    this.userObj.intro = res1.data.data.intro
    // 得到用户个人资料
    var res2 = await apiGetprofile()
    this.userObj.gender = res2.data.data.gender
    this.userObj.birthday = res2.data.data.birthday
  },
  components: {
    upload
  }
}
</script>

<style lang="less">
.van-nav-bar.van-hairline--bottom {
    background-color: #3e9df8;
    .van-nav-bar__title {
        color: #fff;
    }
}

i.van-icon.van-icon-arrow-left.van-nav-bar__arrow {
    color: #fff;
}

span.van-nav-bar__text {
    color: #fff;
}

.van-nav-bar__text:active {
    background-color: #3e9df8 !important;
    color: #000;
}

.userImg {
    width: 25px;
    height: 25px;
    border-radius: 50%;
}
</style>
